package com.gjy.redis.util.jedis;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-09-30 09:19:12
 */
@Component
public class SortedSetRedisUtil {

    @Resource
    private JedisPool jedisPool;

    /**
     * 添加元素到有序集合
     */
    public Long zadd(String key, double score, String member) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zadd(key, score, member);
        }
    }

    /**
     * 批量添加元素到有序集合
     */
    public Long zadd(String key, Map<String, Double> scoreMembers) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zadd(key, scoreMembers);
        }
    }

    /**
     * 获取有序集合元素数量
     */
    public Long zcard(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zcard(key);
        }
    }

    /**
     * 获取元素在有序集合中的排名（从小到大）
     */
    public Long zrank(String key, String member) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrank(key, member);
        }
    }

    /**
     * 获取元素在有序集合中的排名（从大到小）
     */
    public Long zrevrank(String key, String member) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrevrank(key, member);
        }
    }

    /**
     * 获取元素的分数
     */
    public Double zscore(String key, String member) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zscore(key, member);
        }
    }

    /**
     * 获取有序集合指定范围的元素（按分数从小到大）
     */
    public Set<String> zrange(String key, long start, long end) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrange(key, start, end);
        }
    }

    /**
     * 获取有序集合指定范围的元素（按分数从大到小）
     */
    public Set<String> zrevrange(String key, long start, long end) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrevrange(key, start, end);
        }
    }

    /**
     * 获取有序集合指定分数范围的元素
     */
    public Set<String> zrangeByScore(String key, double min, double max) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrangeByScore(key, min, max);
        }
    }

    /**
     * 移除有序集合中的元素
     */
    public Long zrem(String key, String... members) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrem(key, members);
        }
    }

    /**
     * 增加元素的分数
     */
    public Double zincrby(String key, double increment, String member) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zincrby(key, increment, member);
        }
    }

}
